import React from 'react';
import {Upload,Avatar,} from 'antd';
import {AnyAction, Dispatch} from "redux";

import { PlusOutlined } from '@ant-design/icons';
import {connect} from "dva";
import documentService from '@/services/document'
import {UploadRequestOption as RcCustomRequestOptions} from "rc-upload/lib/interface";

interface Props{
  dispatch:Dispatch<AnyAction>;
  value?: string | number;
  onChange?:(value:string | number)=>void;
}

interface State {
  value?: (string | number);
}

class FormAvatar extends React.PureComponent<Props, State> {

  state = {
    value:this.props.value
  };

  static getDerivedStateFromProps(nextProps: Props) {
    if ('value' in nextProps) {
      return { value: nextProps.value };
    }
    return null;
  }

  customRequest = (options:RcCustomRequestOptions) => {
    const file=options.file;
    const {dispatch,onChange}=this.props;
    if(file){
      dispatch({
        type:'document/upload',
        payload:file
      })
      // @ts-ignore
      .then((data)=>{
        if(data&&data.id){
          onChange&&onChange(data.id);
        }
      });
    }
  };

  render () {
    const {value}=this.state;
    return (
      <Upload
        accept="image/png"
        showUploadList={false}
        listType="picture-card"
        customRequest={this.customRequest}
      >
        {value ? (
          <Avatar size={64} src={documentService.download(value)} />
        ):(
          <>
            <PlusOutlined />
            <div className="ant-upload-text">请上传</div>
          </>
        )}
      </Upload>
    )
  }
}

export default connect()(FormAvatar);


